import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
// 重新push方法 
const push = VueRouter.prototype.push
VueRouter.prototype.push = function (location) {
  // 主要添加 异步捕获 catch 函数
  return push.call(this, location).catch(e => e)
}


const routes = [
  // 路由重定向
  {
    path: '/',
    redirect: '/home/bookshop'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '@/views/login')
  },
  {
    path: '/home',
    name: 'home',
    component: () => import(/* webpackChunkName: "home" */ '@/views/home'),
    children: [{
      path: '/home/bookshop',
      name: 'bookShop',
      component: () => import(/* webpackChunkName: "bookShop" */ '@/views/home/bookShop')
    },{
      path: '/home/bookcollect',
      name: 'bookCollect',
      component: () => import(/* webpackChunkName: "bookCollect" */ '@/views/home/bookCollect')
    },{
      path: '/home/my',
      name: 'my',
      component: () => import(/* webpackChunkName: "my" */ '@/views/home/my'),
      // 元信息
      meta: {
        requireLogin: true
      }
    }]
  },
  {
    path: '/detail/:id',
    name: 'detail',
    component: () => import(/* webpackChunkName: "detail" */ '@/views/detail')
  },
  {
    path: '/search',
    name: 'search',
    component: () => import(/* webpackChunkName: "search" */ '@/views/search')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由拦截
router.beforeEach((to, from, next) => {
  // 拦截跳转路由 元信息需要登录的
  // 但是本地存储没有token
  if(to.meta.requireLogin && !localStorage.getItem('token')) {
    // 拦截进入登录页面
    next('/login')
  } else {
    // 正常跳转
    next()
  }
})

export default router
